package com.test.resumeanalysis

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.OpenableColumns
import android.util.Log

import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.itextpdf.text.Document
import com.itextpdf.text.pdf.PdfWriter
import com.setruth.mvvmbaseproject.network.ApiResponse
import com.setruth.mvvmbaseproject.network.api.UpLoadAPi
import com.setruth.mvvmbaseproject.util.LogUtil
import com.test.resumeanalysis.common.BaseVBActivity
import com.test.resumeanalysis.data.model.UpLoadBean
import com.test.resumeanalysis.databinding.ActivityMainBinding
import com.test.resumeanalysis.util.FileUtil

import com.test.resumeanalysis.util.FileUtil.createTxtFile
import com.test.resumeanalysis.view.ResumePopupWindow
import com.test.resumeanalysis.viewModel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.poi.xwpf.usermodel.XWPFDocument
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

class MainActivity : BaseVBActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    companion object {
        const val PICK_PHOTO = 100001
        const val PICK_FILE = 100002
    }

    private val model: PublicViewModel by viewModels()
    private lateinit var navController: NavController


    override fun onInit(savedInstanceState: Bundle?) {


        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment
        navController = navHostFragment.findNavController()
//        NavigationUI.setupWithNavController(binding!!.navMain, navController)

        binding.navMain.setOnItemSelectedListener {
            if (it.isChecked) {
                return@setOnItemSelectedListener true
            }
            when (it.itemId) {
                R.id.menu_home -> {
                    navController.navigate(R.id.menu_home)
                }
                R.id.menu_talent -> {
                    navController.navigate(R.id.menu_talent)
                }
                R.id.menu_resume -> {

                    val mPopupWindow =
                        ResumePopupWindow(this, object : ResumePopupWindow.OnClickListener {
                            override fun picOnClick() {
                                openAlbum()
                            }

                            override fun pdfOnClick() {
                                pickFile()
                            }

                            override fun cancel() {
                                LogUtil.e("取消")

                            }
                        })
                    mPopupWindow.setDialogMessage("");
                    mPopupWindow.show(binding.root);
                    return@setOnItemSelectedListener false
                }
            }
            true
        }

        navController.addOnDestinationChangedListener { _, destination, _ ->
            when (destination.id) {
                R.id.menu_home, R.id.menu_post, R.id.menu_talent -> {
                    showBottomNav()
                }
                R.id.menu_resume -> {
                    showBottomNav()
                }
                else -> {
                    hideBottomNav()
                }
            }
        }

    }

    suspend fun initWeb(base64: String) {
        model.apply {
            val upLoadBean = UpLoadBean(base64);
            request(UpLoadAPi::class.java).uploadFile(upLoadBean).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> LogUtil.e("${it.errMsg} ${it.exception}")
                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            LogUtil.e(it.toString())
                        }
                    }
                }
            }

        }
    }

    /**
     * BottomNav显示控制
     */
    private var isShowBottomNav = true

    /**
     * 显示导航
     */
    private fun showBottomNav() {
        if (!isShowBottomNav) {
            binding.navMain.visibility = View.VISIBLE
            isShowBottomNav = true
        }
    }

    /**
     * 隐藏导航
     */
    private fun hideBottomNav() {
        if (isShowBottomNav) {
            binding.navMain.visibility = View.GONE
            isShowBottomNav = false
        }
    }


    private fun openAlbum() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = "android.intent.action.GET_CONTENT"
        intent.addCategory("android.intent.category.OPENABLE")
        startActivityForResult(intent, PICK_PHOTO)
    }


    private fun pickFile() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        startActivityForResult(intent, PICK_FILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PICK_PHOTO ->
                    data?.data?.let { uri ->
                        LogUtil.e(uri.toString())
                        val realPath = FileUtil.getFileRealPath(this@MainActivity, uri)
                        realPath?.let {
                            GlobalScope.launch {
                                withContext(Dispatchers.IO) {
                                    val filePath = it
                                    LogUtil.e(it)
                                    val base64 = FileUtil.jpgToBase64(filePath)
                                    val filePath2 = cacheDir.absolutePath + "/test2.txt"
                                    createTxtFile(filePath2, base64)
                                    initWeb(base64)
                                }
                            }
                        }
                    }
                PICK_FILE -> {
                    data?.data?.let { uri ->
                        uri.apply {
                            val realPath = FileUtil.getFileRealPath(this@MainActivity, uri)
                            val file = realPath?.let {
                                LogUtil.e(it)
                                val file = File(it)
                                GlobalScope.launch {
                                    withContext(Dispatchers.IO) {
//                                        val filePath = cacheDir.absolutePath+"/test.txt"
//                                        val content = "This is the content of the file."
//                                        createTxtFile(filePath, content)
                                        val filePath = it
                                        LogUtil.e(it)
                                        val base64 = FileUtil.filetoBase64(filePath)
//                                        LogUtil.e(base64)
//                                        val filePath2 = cacheDir.absolutePath+"/test2.txt"
//                                        createTxtFile(filePath2,base64)
                                        LogUtil.e(filePath)
                                        initWeb(base64)
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }


}